package com.study.www.config;

import com.study.www.test2.entity.Logger;
import com.study.www.test2.entity.LoggerRepository;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 日志AOP切面
 *
 * @author : 89007337.zhuyanpeng
 * @date :Create in  2019/8/20- 15:04
 **/
@Aspect
@Slf4j
@Component
public class LogAspect {
    @Autowired
    LoggerRepository loggerRepository;


    @Pointcut("@annotation(com.study.www.config.WebLog)")
    public void log(){

    }

    @Around("log()")
    public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable{
        Logger logger = new Logger();
        long beginTime = System.currentTimeMillis();
        Object proceed = joinPoint.proceed();
        long endTime = System.currentTimeMillis();
        WebLog webLog = ((MethodSignature) joinPoint.getSignature()).getMethod().getAnnotation(WebLog.class);
        String description = webLog.value();
        logger.setId(IdWorks.getId());
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        logger.setUrl(request.getRequestURL().toString());
        logger.setDescription(description);
        logger.setHttpMethod(request.getMethod());
        logger.setClassName(joinPoint.getSignature().getDeclaringTypeName()+"["+joinPoint.getSignature().getName()+"]");
        logger.setIpAddress(getIpAddress(request));
        logger.setTime(endTime-beginTime);
        logger.setCreateTime(new Date());
        loggerRepository.save(logger);
        return proceed;
    }

    public final static String getIpAddress(HttpServletRequest request)  {
        // 获取请求主机IP地址,如果通过代理进来，则透过防火墙获取真实IP地址
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }
        return ip;
    }

}
